/**
 * 通过记录数据生成tree
 * @param records
 * @param idKey
 * @param pidKey
 * @param childrenKey
 * @param sortKey
 * @param callback
 * @constructor
 */
export function GeneratorTree(records, idKey, pidKey, childrenKey, sortKey, callback) {

    records.sort(function (a, b) {
        if (a[pidKey] === b[pidKey]) {
            return b[sortKey] - a[sortKey]
        } else {
            return a[pidKey] - b[pidKey]
        }
    })

    this.default = null

    let groups = {}
    records.forEach((item, key) => {
        if (item['default'] && item['default'] === true) {
            this.default = {name: item.name, value: item.title, id: item.id, iconCls: item.iconCls}
        }
        let group = groups[item[pidKey]] || []
        group.push(item)
        groups[item[pidKey]] = group
    })

    let childNode = function (root) {
        let data = []
        groups[root].forEach(item => {
            let node = callback(item)
            if (groups[item[idKey]]) {
                node[childrenKey] = childNode(item[idKey])
            }
            data.push(node)
        })
        return data
    }

    this.tree = (root) => {
        return childNode(root)
    }
}